package com.ekuaitu.kuaitustaff.activity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.ekuaitu.kuaitustaff.BuildConfig;
import com.ekuaitu.kuaitustaff.R;
import com.ekuaitu.kuaitustaff.api.ApiService;
import com.ekuaitu.kuaitustaff.api.ApiStore;
import com.ekuaitu.kuaitustaff.api.UrlConstant;
import com.ekuaitu.kuaitustaff.application.MyApplication;
import com.ekuaitu.kuaitustaff.base.BaseActivity;
import com.ekuaitu.kuaitustaff.bean.GetCodeBean;
import com.ekuaitu.kuaitustaff.bean.LogInBeanNew;
import com.ekuaitu.kuaitustaff.utils.AppManager;
import com.ekuaitu.kuaitustaff.utils.CheckRegexUtils;
import com.ekuaitu.kuaitustaff.utils.Constants;
import com.ekuaitu.kuaitustaff.utils.Logger;
import com.ekuaitu.kuaitustaff.utils.SPKey;
import com.ekuaitu.kuaitustaff.utils.SPUtils;
import com.ekuaitu.kuaitustaff.utils.ToastUtils;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginNewActivity extends BaseActivity {


    @BindView(R.id.login_phoneNum)
    EditText loginPhoneNum;
    @BindView(R.id.login_getSms)
    TextView loginGetSms;
    @BindView(R.id.login_smsCode)
    EditText loginSmsCode;
    @BindView(R.id.login_confirm)
    TextView loginConfirm;
    @BindView(R.id.iv_clear)
    ImageView iv_clear;
    @BindView(R.id.btn_change)
    Button btn_change;

    @BindView(R.id.layout_content)
    LinearLayout layout_content;
    @BindView(R.id.layout_scrollView)
    ScrollView layout_scrollView;
    @BindView(R.id.iv_log)
    ImageView iv_log;


    private int screenHeight = 0;//屏幕高度
    private int keyHeight = 0; //软件盘弹起后所占高度
    private float scale = 0.6f; //logo缩放比例

    private PushAgent mPushAgent;
    private String phoneNum;
    private String smsCode;
    private Context mContext = this;
    private int seconds = 60;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if (seconds > 0) {
                        if (loginGetSms != null) {
                            loginGetSms.setClickable(false);
                            loginGetSms.setText(seconds-- + "s");
                            //每过1000毫秒发送消息
                            handler.sendEmptyMessageDelayed(0, 1000);
                        }
                    } else {
                        seconds = 60;
                        loginGetSms.setClickable(true);
                        loginGetSms.setText("获取验证码");
                        checkPhoneNum();
                    }
                    break;
            }
        }
    };

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initData() {

        mPushAgent = PushAgent.getInstance(this);
        mPushAgent.onAppStart();
        try {
            mPushAgent.deleteAlias(((MyApplication) getApplication()).getUserId(), "STAFF", new UTrack.ICallBack() {
                @Override
                public void onMessage(boolean b, String s) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        SPUtils.getInstance(mContext).clearSharePreference();
        ((MyApplication) getApplication()).setUserId(null);
        ((MyApplication) getApplication()).setToken(null);
        ((MyApplication) getApplication()).setHeaderToken(null);

        screenHeight = this.getResources().getDisplayMetrics().heightPixels; //获取屏幕高度
        keyHeight = screenHeight / 5;//弹起高度为屏幕高度的1/5
        showLogAnim();

        loginPhoneNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                checkPhoneNum();
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s) && iv_clear.getVisibility() == View.GONE) {
                    iv_clear.setVisibility(View.VISIBLE);

                } else if (TextUtils.isEmpty(s)) {
                    iv_clear.setVisibility(View.GONE);
                }
            }
        });
        loginSmsCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(loginSmsCode.getText().toString()) && loginSmsCode.getText().length() == 4 && !TextUtils.isEmpty(loginPhoneNum.getText().toString())) {
                    loginConfirm.setBackgroundResource(R.drawable.btn_bg);
                    loginConfirm.setClickable(true);

                } else {
                    loginConfirm.setBackgroundResource(R.drawable.btn_gray_bg);
                    loginConfirm.setClickable(false);

                }

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(loginSmsCode.getText().toString()) && loginSmsCode.getText().length() == 4 && !TextUtils.isEmpty(loginPhoneNum.getText().toString())) {
                    loginConfirm.setBackgroundResource(R.drawable.btn_bg);
                    loginConfirm.setClickable(true);

                } else {
                    loginConfirm.setBackgroundResource(R.drawable.btn_gray_bg);
                    loginConfirm.setClickable(false);

                }
            }
        });
    }


    @Override
    public void initView() {
        if (BuildConfig.DEBUG) {
            btn_change.setVisibility(View.VISIBLE);
        } else {
            btn_change.setVisibility(View.GONE);
        }
        loginGetSms.setClickable(false);
        loginConfirm.setClickable(false);

    }

    @OnClick({R.id.login_getSms, R.id.login_confirm, R.id.iv_clear, R.id.btn_change})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_getSms:
                phoneNum = loginPhoneNum.getText().toString() + "";
                if (CheckRegexUtils.checkPhoneNum(phoneNum)) {
                    loginGetSms.setClickable(false);
                    sendSms(phoneNum);
                } else {
                    ToastUtils.makeText(mContext, getResources().getString(R.string.inputPhoneNum), ToastUtils.LENGTH_SHORT).show();
                }
                break;
            case R.id.login_confirm:
                MobclickAgent.onEvent(this, Constants.PHONE_VERIFICATION);
                smsCode = loginSmsCode.getText().toString();
                phoneNum = loginPhoneNum.getText().toString();
                if (CheckRegexUtils.checkPhoneNum(phoneNum)) {
                    if (!smsCode.equals("") && smsCode.length() == 4) {
                        login(phoneNum, smsCode);
                    } else {
                        ToastUtils.makeText(mContext, "请输入4位验证码", 1, ToastUtils.LENGTH_SHORT).show();
                    }
                } else {
                    ToastUtils.makeText(mContext, getResources().getString(R.string.inputPhoneNum), 1, ToastUtils.LENGTH_SHORT).show();
                }
                break;
            case R.id.iv_clear:
                loginPhoneNum.setText("");
                loginGetSms.setTextColor(getResources().getColor(R.color.black2));
                break;
            case R.id.btn_change:
                startActivity(new Intent(mContext, DebugModeActivity.class));
                break;
        }
    }

    private void sendSms(final String phoneNum) {
        showLoadingDialog("正在发送...");
        HashMap<String, String> eventMap = new HashMap<>();
        eventMap.put("action", "用户获取验证码");
        eventMap.put("comment", "获取验证码");
        eventMap.put("user_account", phoneNum);
        new ApiStore().getApiService(UrlConstant.Request.BASE_URL_NEW, "login/getCode.json", eventMap, new ApiStore.ParseCallBack() {

            @Override
            public void onSaveFailure(String error) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, error, ToastUtils.LENGTH_SHORT).show();
            }

            @Override
            public void onSaveSuccess(ApiService apiService) {
                apiService.getCode(((MyApplication) getApplication()).getRequestFieldMap(), phoneNum).enqueue(new Callback<GetCodeBean>() {
                    @Override
                    public void onResponse(Call<GetCodeBean> call, Response<GetCodeBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            dismissLoadingDialog();
                            if (response.body().getErrCode().equals("0")) {
                                ToastUtils.makeText(mContext, "验证码发送中", ToastUtils.LENGTH_SHORT).show();
                                //重发验证码倒计时
                                loginGetSms.setTextColor(getResources().getColor(R.color.black2));
                                handler.sendEmptyMessage(0);
                            } else {
                                loginGetSms.setClickable(true);
                                ToastUtils.makeText(mContext, response.body().getMessage(), ToastUtils.LENGTH_SHORT).show();
                            }

                        } else {
                            dismissLoadingDialog();
                            loginGetSms.setClickable(true);
                            ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), 1, ToastUtils.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<GetCodeBean> call, Throwable t) {
                        dismissLoadingDialog();
                        loginGetSms.setClickable(true);
                        ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                        Logger.i("neterror", "004" + t.toString());
                    }
                });
            }
        });
    }

    private void login(final String phoneNum, final String code) {
        showLoadingDialog();
        HashMap<String, String> eventMap = new HashMap<>();
        eventMap.put("action", "用户登陆");
        eventMap.put("comment", "用户登陆");
        eventMap.put("user_account", phoneNum);
        new ApiStore().getApiService(UrlConstant.Request.BASE_URL_NEW, "login/mobile-login.json", eventMap, new ApiStore.ParseCallBack() {
            @Override
            public void onSaveFailure(String error) {
                dismissLoadingDialog();
                ToastUtils.makeText(mContext, error, ToastUtils.LENGTH_SHORT).show();
            }

            @Override
            public void onSaveSuccess(ApiService apiService) {
                apiService.logIn(((MyApplication) getApplication()).getRequestFieldMap(), phoneNum, code).enqueue(new Callback<LogInBeanNew>() {
                    @Override
                    public void onResponse(Call<LogInBeanNew> call, Response<LogInBeanNew> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            dismissLoadingDialog();
                            if (response.body().getErrCode() == 0) {
                                Logger.i("parse", "retrofitRes" + "登录成功" + response.body().getAttachment().getUserModel().getName() + "x-incar-token=" + response.headers().get("x-incar-token"));
                                ToastUtils.makeText(mContext, getResources().getString(R.string.loginSuccess), ToastUtils.LENGTH_SHORT).show();
                                try {
                                    mPushAgent.deleteAlias(((MyApplication) getApplication()).getUserId(), "STAFF", new UTrack.ICallBack() {
                                        @Override
                                        public void onMessage(boolean b, String s) {

                                        }
                                    });
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                LogInBeanNew.AttachmentBean.UserModelBean userModel = response.body().getAttachment().getUserModel();
                                ((MyApplication) getApplication()).setUserId(userModel.getUserId());
                                ((MyApplication) getApplication()).setuserName(userModel.getName());
                                ((MyApplication) getApplication()).setToken(userModel.getToken());
                                ((MyApplication) getApplication()).setHeaderToken(response.headers().get("x-incar-token"));
                                SPUtils.getInstance(mContext).putStringValue(SPKey.USER_ID, userModel.getUserId());
                                SPUtils.getInstance(mContext).putStringValue(SPKey.USER_NAME, userModel.getName());
                                SPUtils.getInstance(mContext).putStringValue("userCity", userModel.getUserCity());
                                SPUtils.getInstance(mContext).putStringValue(SPKey.USER_PHONE_NUM, userModel.getPhoneNum());
                                SPUtils.getInstance(mContext).putStringValue("userType", userModel.getUserType());
                                SPUtils.getInstance(mContext).putIntValue("businessType", userModel.getBusinessType());
                                SPUtils.getInstance(mContext).putStringValue("pushAlias", userModel.getPushAlias());
                                SPUtils.getInstance(mContext).putStringValue("pushTag", userModel.getPushTag());
                                SPUtils.getInstance(mContext).putStringValue("pushUserType", userModel.getPushUserType());


                                try {
                                    mPushAgent.addAlias(((MyApplication) getApplication()).getUserId(), "STAFF", new UTrack.ICallBack() {
                                        @Override
                                        public void onMessage(boolean b, String s) {

                                        }
                                    });
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }


                                Intent intent = new Intent(mContext, CarNewMainMapActivity.class);
                                intent.putExtra("intentFrom",2);
                                startActivity(intent);
                                AppManager.getAppManager().finishActivity();
                            } else {
                                dismissLoadingDialog();
                                ToastUtils.makeText(mContext, response.body().getMessage(), 1, ToastUtils.LENGTH_SHORT).show();
                            }
                        } else {
                            dismissLoadingDialog();
                            ToastUtils.makeText(mContext, getResources().getString(R.string.serverError), 1, ToastUtils.LENGTH_SHORT).show();
                        }
                    }


                    @Override
                    public void onFailure(Call<LogInBeanNew> call, Throwable t) {
                        dismissLoadingDialog();
                        ToastUtils.makeText(mContext, getResources().getString(R.string.badNetwork), ToastUtils.LENGTH_SHORT).show();
                        Logger.i("neterror", "005");
                    }
                });
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    private void checkPhoneNum() {
        if (CheckRegexUtils.checkPhoneNum(loginPhoneNum.getText().toString())) {
            loginGetSms.setTextColor(getResources().getColor(R.color.login_getCode));
            loginGetSms.setClickable(true);
        } else {
            loginGetSms.setTextColor(getResources().getColor(R.color.black2));
            loginGetSms.setClickable(false);
        }
    }

    private void showLogAnim() {

        layout_scrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        layout_scrollView.addOnLayoutChangeListener(new ViewGroup.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {


                if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
                    int dist = (layout_content.getBottom() - bottom) / 3;
                    if (dist > 0) {
                        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(layout_content, "translationY", 0.0f, -dist);
                        mAnimatorTranslateY.setDuration(300);
                        mAnimatorTranslateY.setInterpolator(new LinearInterpolator());
                        mAnimatorTranslateY.start();
                        zoomIn(iv_log, dist);
                    }

                } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
                    if ((layout_content.getBottom() - oldBottom) > 0) {
                        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(layout_content, "translationY", layout_content.getTranslationY(), 0);
                        mAnimatorTranslateY.setDuration(300);
                        mAnimatorTranslateY.setInterpolator(new LinearInterpolator());
                        mAnimatorTranslateY.start();
                        //键盘收回后，logo恢复原来大小，位置同样回到初始位置
                        zoomOut(iv_log);
                    }
                }
            }
        });
    }

    /**
     * 缩小
     *
     * @param view
     */
    public void zoomIn(final View view, float dist) {
        view.setPivotY(view.getHeight());
        view.setPivotX(view.getWidth() / 2);
        AnimatorSet mAnimatorSet = new AnimatorSet();
        ObjectAnimator mAnimatorScaleX = ObjectAnimator.ofFloat(view, "scaleX", 1.0f, scale);
        ObjectAnimator mAnimatorScaleY = ObjectAnimator.ofFloat(view, "scaleY", 1.0f, scale);
        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(view, "translationY", 0.0f, -dist);

        mAnimatorSet.play(mAnimatorTranslateY).with(mAnimatorScaleX);
        mAnimatorSet.play(mAnimatorScaleX).with(mAnimatorScaleY);
        mAnimatorSet.setDuration(300);
        mAnimatorSet.start();
    }

    //放大
    public void zoomOut(final View view) {
        view.setPivotY(view.getHeight());
        view.setPivotX(view.getWidth() / 2);
        AnimatorSet mAnimatorSet = new AnimatorSet();

        ObjectAnimator mAnimatorScaleX = ObjectAnimator.ofFloat(view, "scaleX", scale, 1.0f);
        ObjectAnimator mAnimatorScaleY = ObjectAnimator.ofFloat(view, "scaleY", scale, 1.0f);
        ObjectAnimator mAnimatorTranslateY = ObjectAnimator.ofFloat(view, "translationY", view.getTranslationY(), 0);

        mAnimatorSet.play(mAnimatorTranslateY).with(mAnimatorScaleX);
        mAnimatorSet.play(mAnimatorScaleX).with(mAnimatorScaleY);
        mAnimatorSet.setDuration(300);
        mAnimatorSet.start();
    }
}


